﻿using System;
using System.Collections.Generic;
using System.Text;
using UnityExtensions;

namespace CxExtension
{
	public class Counter<T>
	{
		private ObjectPool<CountInfo<T>> mPool = new ObjectPool<CountInfo<T>>();                      //
		private Dictionary<T, CountInfo<T>> mCountMap = new Dictionary<T, CountInfo<T>>();                      //
		private static StringBuilder bld = new StringBuilder();
		public void Add(T key)
		{
			var info = mCountMap.GetOrNewAddF(key, it =>
			{
				var countInfo = mPool.Get();
				countInfo.Key = key;
				countInfo.Init();
				return countInfo;
			});
			info.Count += 1;
		}

		public bool Contain(T key)
		{
			return mCountMap.ContainsKey(key);
		}
		public bool Remove(T key)
		{
			CountInfo<T> info;
			if (mCountMap.TryGetValue(key, out info))
			{
				info.Count -= 1;
				if (info.Count <= 0)
				{
					mCountMap.Remove(key);
					mPool.Recycle(info);
				}

				return true;
			}

			return false;
		}

		public int Count { get { return mCountMap.Count; } }

		public override string ToString()
		{
			return ToString(null);
		}
		public string ToString(Action<StringBuilder,CountInfo<T>> callAction)
		{
			//var bld = new StringBuilder();
			if (mCountMap.Count > 0)
			{
				bld.AppendFormatLine("Counter has:{0}", mCountMap.Count);
				foreach (var it in mCountMap)
				{
					bld.AppendLine(it.Value.ToString());
					callAction?.Invoke(bld, it.Value);
				}
			}

			var str = bld.ToString();
			bld.Clear();
			return str;
		}


	}
}